import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { CreateAuthDto } from './dto/create-auth.dto';
import { PrismaService } from 'src/prisma/prisma.service';
import { LoginAuthDto } from './dto/login-auth.dto';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class AuthService {
  constructor(
    private readonly prismaService: PrismaService,
    private readonly jwtService: JwtService,
  ) {}
  async create(createAuthDto: CreateAuthDto) {
    try {
      const user = await this.prismaService.user.findUnique({
        where: {
          username: createAuthDto.username,
        },
      });

      if (user) {
        throw new HttpException('User already exists', HttpStatus.BAD_REQUEST);
      }

      await this.prismaService.user.create({
        data: createAuthDto,
      });
      return { message: 'User created successfully' };
    } catch (error) {
      throw new HttpException(error.message, 400);
    }
  }

  async login(loginAuthDto: LoginAuthDto) {
    try {
      const user = await this.prismaService.user.findUnique({
        where: {
          username: loginAuthDto.username,
          password: loginAuthDto.password,
        },
      });

      if (!user) {
        throw new HttpException('账号或密码错误', 400);
      }

      return {
        token: this.jwtService.sign({
          username: user.username,
          id: user.id,
        }),
      };
    } catch (error) {}
  }
}
